// Created by liusc on 2020/8/5-9:24.
import { getDict } from "~/utils";
import {
	getItem,
	getItem2,
	getItem3,
	getItem4,
	getObj,
	addObj3,
	putObj3,
	startBudgetAdd,
	judgeInitiate,
	getInitObj
} from "@/views/wy-budget/api/budgetdeptapply.js";
import uploadMedia from "@/components/upload-media";
import {
	getFiles,
	checkFiles,
	delFiles
} from "@/views/wy-budget/api/fileoperation.js";
import Budget from "@/assets/vue-mixin/budget";
import fileUpload from "@/views/wy-budget/components/fileUpload";

export default {
	name: "apply_add",
	mixins: [Budget],
	components: { uploadMedia, fileUpload },
	data() {
		var doubleValidate = (rule, value, callback) => {
			let reg = /^[0-9]+(.[0-9]{1,2})?$/;
			let lable = rule.message;
			if (!reg.test(value)) {
				return callback(new Error("数值格式错误"));
			} else {
				callback();
			}
		};

		return {
			fileId: "",
			fileId2: "",
			deptId: "",
			isShow: false,
			fileUploadUrl: "/admin/sys-file/upLodeFileEdit",
			uploadFileList: [],
			fileList: [],
			modelType: "budgetApply",
			isEdit: true,
			busId: "",

			form: {
				applyData: {
					applyId: "",
					budgetId: "",
					budgetCode: "",
					applyName: "",
					applyDept: "",
					applyType: "",
					budgetSum: "",
					remarks: "",
					fileId: "",
					fileId2: ""
				},
				itemValueList: [],
				operateType: ""
			},

			rules: {
				applyData: {
					applyName: [
						{
							required: true,
							message: "请输入申请名称",
							trigger: "blur"
						},
						{
							min: 0,
							max: 20,
							message: "长度在 0 到 20 个字符",
							trigger: "blur"
						}
					],
					budgetSum: [
						{
							required: true,
							message: "请输入预算总金额",
							trigger: "blur"
						},
						{ validator: doubleValidate, trigger: "blur" }
					],
					remarks: [
						{
							required: true,
							message: "请输入费用说明",
							trigger: "blur"
						},
						{
							min: 0,
							max: 100,
							message: "长度在 0 到 100 个字符",
							trigger: "blur"
						}
					]
				}
			}
		};
	},

	computed: {
		applyDept2: function() {
			let types = getDict("budget_department");
			let pv = this.form.applyData.applyDept;
			if (pv && types.length > 0) {
				const pts = types.find(t => t.value == pv);
				return pts?.label;
			}
			return "";
		},

		applyType2: function() {
			let types = getDict("budget_type");
			let pv = this.form.applyData.applyType;
			if (pv && types.length > 0) {
				const pts = types.find(t => t.value == pv);
				return pts?.label;
			}
			return "";
		}
	},

	beforeMount() {
		this.fileId = this.$route.query.fileId;
		this.fileId2 = this.$route.query.fileId2;
		this.detpId = this.$route.query.deptId;

		const loading = this.$loading({
			lock: true,
			text: "数据加载中"
		});

		// 获取预算编号，封装数据，初始化科目

		getInitObj(this.detpId)
			.then(respData => {
				this.$refs["add-form"].resetFields();
				this.form.applyData = respData.data.data;
				// 获取科目
				this.initItem(this.form.applyData.budgetId);
				loading.close();
			})
			.catch(e => {
				loading.close();
				this.$message({
					type: "error",
					message: "数据获取失败!"
				});
			});
	},

	methods: {
		// 科目
		initItem(templateName) {
			getItem4(templateName).then(rep => {
				let rspD = rep.data.data;
				rspD &&
					(this.form.itemValueList = rspD.map((item, index) => {
						return {
							...item,
							isNead: "1",
							sortNum: index + 1,
							children: item.children
								? item.children.map(it => ({ ...it, isNead: "1" }))
								: item.children
						};
					}));
			});
		},

		// 取消
		cancel() {
			this.closeNowRouter();
		},

		// cqg校验必输
		checkWillBe() {
			const reg = /^\d{0,15}(\.\d{0,2})?$/;
			let list = this.form.itemValueList.reduce((total, item) => {
				if (item.children) {
					return total.concat(item.children.filter(it => it.isNead != 0));
				} else {
					return item.isNead != 0 ? [...total, item] : total;
				}
			}, []);
			//只有必填的校验合法值
			//let tips = list.find(item => (item.isNead === '1' && (!item.itemValue || !reg.test(`${item.itemValue}`))) || (item.isNead != '1' && !reg.test(`${item.itemValue}`)) )
			//全必填
			let tips = list.find(
				item =>
					item.itemValue == null ||
					item.itemValue == "" ||
					!reg.test(`${item.itemValue}`)
			);
			if (tips) {
				if (tips.itemValue == "" || tips.itemValue == null) {
					this.$message.warning(
						`科目"${tips.itemName} " 金额为空，请输入完整金额`
					);
					return false;
				} else {
					this.$message.warning(
						`科目"${tips.itemName} " 金额不正确，请输入合理金额`
					);
					return false;
				}
			}
			return true;
		},

		// 保存
		addCommit() {
			this.checkWillBe() &&
				this.$refs["add-form"].validate(valid => {
					valid && this.$refs.fileUpload.submit();
				});
		},

		sendFormData(val) {
			if (val && this.isEdit) {
				//this.form.applyData.fileId2 = val;
				//this.busId = val;
				//this.isEdit = false;
			}

			this.form.applyData.fileId = this.$route.query.fileId;
			this.form.applyData.fileId2 = this.$route.query.fileId2;

			addObj3(this.form)
				.then(rep => {
					getObj(rep.data.msg)
						.then(respData => {
							startBudgetAdd(respData.data.data)
								.then(respData => {})
								.catch(e => {});
						})
						.catch(e => {});

					this.success_message("保存成功");
					//this.loadClose();
					this.closeNowRouter();
				})
				.catch(e => {
					this.errormessage("保存失败");
					//this.loadClose();
				});

			this.closeNowRouter();
		},

		success_message(msg) {
			this.$message({
				type: "success",
				message: msg
			});
		},

		errormessage(msg) {
			this.$message({
				type: "error",
				message: msg
			});
		},

		closeNowRouter() {
			//关闭当前新增页，暂时没找到好办法
			this.$store.commit("delHistoryRoute", this.$route.fullPath);
			//跳转
			this.$router.push({ name: "deptapply_list" });
		},

		// 上传成功监听
		handleCompleted(data) {
			this.sendFormData(data);
		},

		onSuccess(rep, file, fileList) {
			//文件上传成功，开始保存表单
			if (rep.data != null) {
				this.sendFormData(rep.data);
			} else {
				this.err("提交失败");
			}
		},

		onError(err, file, fileList) {
			this.err("提交失败");
		},

		beforeUpload() {},

		// 下载
		handleClean(file) {
			this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			})
				.then(() => {
					delFiles(file.fileId, this.modelType).then(resp => {
						if (resp.data.code === 0) {
							this.$message({
								type: "success",
								message: "删除成功!"
							});

							//this.fileList = []
							this.fileList = this.fileList.filter(
								file => file.fileId != fileId
							);
						} else {
							this.$message({
								type: "error",
								message: "删除失败!"
							});
						}
					});
				})
				.catch(() => {
					this.$message({
						type: "info",
						message: "已取消删除"
					});
				});
		}
	}
};
